from rest_framework.response import Response
from rest_framework.generics import RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.viewsets import ModelViewSet
from users.models import User
from users.serializers.userinfo import UpdateMyfileSerializer, UserInfoModelSerialzier, \
    UserPasswordModelSerializer


class PersonMyfileView(RetrieveAPIView, UpdateAPIView):
    # permission_classes = [IsAuthenticated]
    """获取和修改个人信息详情"""

    # 根据不同的请求方式返回不同的序列化器类
    def get_serializer_class(self):
        if self.request.method == 'GET':
            return UserInfoModelSerialzier
        else:
            return UpdateMyfileSerializer

    def get_object(self):
        """自定义查询集"""
        return self.request.user


class ModifyPasswordView(UpdateModelMixin, GenericAPIView):
    serializer_class = UserPasswordModelSerializer
    queryset = User.objects.all()

    def put(self, request):
        instance = request.user
        serializer = self.get_serializer(instance, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)


class UserfollowModelView(UpdateModelMixin, GenericAPIView):
    # queryset = User.objects.all()

    def update(self, request, *args, **kwargs):

        try:
            follow_user = User.objects.get(id=int(args[0]))

        except User.DoesNotExist:

            return Response({'message': '用户不存在',
                             'success': False})

        user = request.user

        if user is not None and user.is_authenticated:

            if user not in follow_user.fans.all():

                follow_user.fans.add(user)

                follow_user.save()

                return Response({'message': '收藏成功',
                                 'success': True})
            else:

                follow_user.fans.remove(user)

                follow_user.save()

                return Response({'message': '取消收藏成功',
                                 'success': True})

        return Response({'message': '用户未登录',
                         'success': False})

    def post(self, request, pk):
        return self.update(request, pk)

    def delete(self, request, pk):
        return self.update(request, pk)
